<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-input v-model="search.keyWord" placeholder="关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getMenus">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="菜单名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="url" label="菜单地址" width="150" sortable>
      </el-table-column>
      <el-table-column prop="icon" label="菜单图标" width="180" sortable>
      </el-table-column>
      <el-table-column prop="children.name" label="父级菜单" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
              @size-change: 当涉及的每页条数发生改变的时候触发的函数
              @current-change: 页数发生改变
              :current-page: 当前第几页
              :page-sizes="[3, 5, 7, 9]": 设定每页的条数
              :page-size="this.search.pageSize": 每页的条数
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.search.currentPage"
          :page-sizes="[3, 5, 7, 9,10]"
          :page-size="this.search.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float: right">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单地址" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="saveForm.icon" auto-complete="off"></el-input>
        </el-form-item>
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
<!--        <el-form-item label="父级菜单" prop="parent">-->
<!--          <el-select v-model="saveForm.parent" clearable value-key="id" placeholder="请选择">-->
<!--            <el-option-->
<!--                v-for="item in parentMenus"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item">-->
<!--              <span style="float: left">{{ item.name }}</span>-->
<!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="父级菜单">
          <el-cascader v-model="saveForm.children"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {
      search: {
        keyWord: "",
        pageSize: 10,
        currentPage: 1
      },
      pageInfo: {
        list: [],
        total: 0
      },
      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //编辑界面数据 不能把null赋值给对象
      saveForm: {
        id: null,
        name: '',
        url: '',
        icon: '',
        children:{
          id:null,
          name: ''
        }
      },
      parentMenus:[],
      deptTree:[]
    }
  },
  methods: {
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleSizeChange(val) {
      // 每页条数
      this.search.pageSize = val;
      this.search.currentPage = 1;
      this.getMenus();
    },
    handleCurrentChange(val) {
      this.search.currentPage = val;
      this.getMenus();
    },
    // 获取联级部门的id和name
    getTree(){
      this.$http.get("/menu/tree")
          .then(result =>{
            // console.log("dajiahoa",result)
            this.deptTree = result.data.data;
          })
          .catch(result =>{

          })
    },
    // 获取部门主管信息
    getParentMenus(){
      this.$http.get("/menu")
          .then(result =>{
            // console.log(result.data)
            let data = result.data;
            if (data.success){
              this.parentMenus = data.data;
            }
          })
          .catch(result => {

          })
    },
    //获取部门列表
    getMenus() {
      // this.listLoading = true;
      // 发送axios请求
      this.$http.post("/menu", this.search)
          .then(result => {
            console.log(result);
            let data = result.data;
            if (data.success) {
              // this.pageInfo.list = data.data.list;
              // this.pageInfo.total = data.data.total;
              this.pageInfo = data.data;
            }
            this.listLoading = false;
          })
          .catch(result => {

          });
    },
    //删除
    handleDel: function (index, row) {
      // console.log(row)
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/menu/" + row.id)
            .then(result => {
              let data = result.data;
              if (data.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.search.currentPage = 1;
                this.getMenus();
                this.listLoading = false;
              }
            })
            .catch(result => {

            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      // console.log("this.saveForm",this.saveForm)
      if (!row.parent){
        this.saveForm.parent = {id:null,username: ""}
      }else {
        // 如果父部门不为空,获取path
        let split = row.path.split("/");
        // console.log(split)
        let path = [];
        // 从一开始因为split数组里第一个元素为'',最后一位为自己的id,也不需要,所以是length-1
        for (let i = 1; i < split.length-1; i++) {
          // push往数组中添加,pop是移除
          path.push(Number.parseInt(split[i]));
          this.saveForm.parent = path;
        }
      }
      this.getParentMenus();
      // this.getTree();
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
          id: null,
          name: '',
          url: '',
          icon: '',
          parent:{
            id:null,
            name: ''
          }
        };
      this.getParentMenus();
      // this.getTree();
    },
    //编辑
    editSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            // 判断,如果父部门不为空,就转换成对象,原本是数组
            // console.log(this.saveForm.parent);
            // console.log(this.saveForm.parent.id);
            // 有可能长度为0
            if (this.saveForm.parent.length >= 0){
              if (this.saveForm.parent.length == 0){
                this.saveForm.parent = {
                  id:null
                }
              }else {
                this.saveForm.parent = {
                  id:this.saveForm.parent[this.saveForm.parent.length-1]
                }
              }
            }
            this.$http.put("/menu",this.saveForm)
                .then(result => {
                  let data = result.data;
                  if (data.success){
                    this.$message({
                      message: '操作成功',
                      type: 'success'
                    });
                    this.search.currentPage = 1;
                    this.getMenus();
                    this.editLoading = false;
                    this.saveFormVisible = false;
                  }
                })
                .catch(result =>{

                })
          });
        }
      });
    },
    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addUser(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getUsers();
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/menu/", ids)
            .then(result => {
              let data = result.data;
              if (data.success) {
                this.$message({
                  message: '批量删除成功',
                  type: 'success'
                });
                this.search.currentPage = 1;
                this.getMenus();
                this.listLoading = false;
              }
            })
            .catch(result => {

            })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getMenus();
  }
}

</script>

<style scoped>

</style>